package com.lcc.bank.tools.template;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.StrUtil;
import freemarker.cache.StringTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.Locale;

/**
 * @author chenlw
 * @version 1.0  2019-01-30
 */
@Component
@Slf4j
public class TemplateHolder {

    private static final String LINE_FEED_REGEX = "\r|\n|\\s";

    private static final String TEMPLATE_BASE_PATH = "template";

    private static Template RECON_BANK_RETURN_MSG_TEMPLATE = null;

    @PostConstruct
    public void init() throws IOException {
        log.info("开始初始化freemarker模板");
        Configuration configuration = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);
        configuration.setEncoding(Locale.getDefault(), CharsetUtil.UTF_8);
        RECON_BANK_RETURN_MSG_TEMPLATE = initFreemarkerTemplate(configuration);
        log.info("freemarker模板初始化完毕");
    }

    public static String getValue(Object dataModel){
        try {
            StringWriter sw = new StringWriter();
            RECON_BANK_RETURN_MSG_TEMPLATE.process(dataModel, sw);
            return sw.toString();
        }catch (Exception e){
            log.error("构造报文时发生异常",e);
            return "构造报文时发生异常";
        }
    }

    private static Template initFreemarkerTemplate(Configuration configuration) throws IOException {
        String templateName = "ReconBankReturnMsgTemplate";
        StringTemplateLoader stringLoader = new StringTemplateLoader();
        ClassPathResource resource = new ClassPathResource(TEMPLATE_BASE_PATH + "/ReconBankReturnMsg.ftl");
        InputStream inputStream = resource.getInputStream();
        String fileContent = IoUtil.read(inputStream,CharsetUtil.GBK);
        //去除换行、空格
        fileContent = fileContent.replaceAll(LINE_FEED_REGEX, StrUtil.EMPTY);
        stringLoader.putTemplate(templateName, fileContent);
        configuration.setTemplateLoader(stringLoader);
        return configuration.getTemplate(templateName, CharsetUtil.GBK);
    }
}
